//
//  CreativeCenterViewController.swift
//  Story
//
//  Created by 汤泽川 on 2019/3/30.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import PKHUD
import CLImagePickerTool

class CreativeCenterViewController: UIViewController {

    let disposeBag = DisposeBag()
    var categoryModel = BehaviorRelay<STStoryCategoryModel>(value: STStoryCategoryModel(channelId: 2, channelName: "经典"))
    
    let titleField = UITextField()
    let titleImageView = UIImageView()
    let contentTextView = UITextView()
    var pickerView : UIPickerView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        buildView()
        initData()
    }
    
    func buildView() {
        let saveBtn = UIBarButtonItem(title: "保存", style: .plain, target: self, action: #selector(saveData))
        let publishBtn = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(publishData))
        self.navigationItem.rightBarButtonItems = [publishBtn, saveBtn]
        let clearBtn = UIBarButtonItem(title: "清空", style: .plain, target: self, action: #selector(clearData))
        self.navigationItem.leftBarButtonItem = clearBtn
        
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(self.view.safeAreaInsets.top + 64)
            make.bottom.equalToSuperview().offset(-(self.view.safeAreaInsets.bottom + 40))
            make.left.right.equalToSuperview()
        }
        let tap = UITapGestureRecognizer(target: self, action: #selector(endEdit))
        scrollView.addGestureRecognizer(tap)
        
        let titleLabel = UILabel()
        titleLabel.font = .boldSystemFont(ofSize: 17)
        titleLabel.textColor = UIColor.init(white: 0, alpha: 0.7)
        titleLabel.text = "标题:"
        scrollView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).inset(18)
            make.top.equalToSuperview().offset(10)
            make.height.equalTo(34)
        }
        
        titleField.placeholder = "给故事取个好听的名字吧~"
        titleField.font = .boldSystemFont(ofSize: 17)
        titleField.textColor = .black
        titleField.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
        titleLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        scrollView.addSubview(titleField)
        titleField.snp.makeConstraints { (make) in
            make.left.equalTo(titleLabel.snp_right).offset(5)
            make.right.equalTo(self.view).inset(18)
            make.centerY.equalTo(titleLabel)
            make.height.equalTo(34)
        }
        let line1 = UIView()
        line1.backgroundColor = UIColor.init(white: 0, alpha: 0.1)
        scrollView.addSubview(line1)
        line1.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp_bottom).offset(5)
            make.left.right.equalTo(self.view)
            make.height.equalTo(0.5)
        }
        
        let categoryTitleLabel = UILabel()
        categoryTitleLabel.font = .boldSystemFont(ofSize: 17)
        categoryTitleLabel.textColor = UIColor.init(white: 0, alpha: 0.7)
        categoryTitleLabel.text = "分类:"
        scrollView.addSubview(categoryTitleLabel)
        categoryTitleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).inset(18)
            make.top.equalTo(line1.snp_bottom).offset(5)
            make.height.equalTo(34)
        }
        let categoryField = UITextField()
        categoryField.isUserInteractionEnabled = false
        categoryField.placeholder = "给作品找个合适的分类吧~"
        categoryField.font = .boldSystemFont(ofSize: 17)
        categoryField.textColor = .black
        categoryField.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
        categoryField.setContentHuggingPriority(.defaultLow, for: .horizontal)
        categoryModel.subscribe(onNext: { (model) in
            categoryField.text = model.channelName
        }).disposed(by: disposeBag)
        scrollView.addSubview(categoryField)
        categoryField.snp.makeConstraints { (make) in
            make.left.equalTo(categoryTitleLabel.snp_right).offset(5)
            make.right.equalTo(self.view).inset(18)
            make.centerY.equalTo(categoryTitleLabel)
            make.height.equalTo(34)
        }
        let selectCategoryBtn = UIButton()
        selectCategoryBtn.addTarget(self, action: #selector(showSelectCategoryView), for: .touchUpInside)
        scrollView.addSubview(selectCategoryBtn)
        selectCategoryBtn.snp.makeConstraints { (make) in
            make.left.top.bottom.equalTo(categoryTitleLabel)
            make.right.equalTo(categoryField)
        }
        let line2 = UIView()
        line2.backgroundColor = UIColor.init(white: 0, alpha: 0.1)
        scrollView.addSubview(line2)
        line2.snp.makeConstraints { (make) in
            make.top.equalTo(categoryTitleLabel.snp_bottom).offset(5)
            make.left.right.equalTo(self.view)
            make.height.equalTo(0.5)
        }
        
        let titleImageLabel = UILabel()
        titleImageLabel.text = "封面(可选)"
        titleImageLabel.font = .systemFont(ofSize: 13)
        titleImageLabel.textColor = UIColor.init(white: 0, alpha: 0.3)
        scrollView.addSubview(titleImageLabel)
        titleImageLabel.snp.makeConstraints { (make) in
            make.top.equalTo(line2.snp_bottom).offset(5)
            make.left.equalTo(titleLabel)
            make.width.equalTo(120)
        }
        
        titleImageView.layer.masksToBounds = true
        titleImageView.layer.cornerRadius = 4
        scrollView.addSubview(titleImageView)
        titleImageView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view).inset(18)
            make.top.equalTo(titleImageLabel.snp_bottom).offset(5)
            make.height.equalTo(titleImageView.snp_width).multipliedBy(9.0/16.0)
        }
        
        let choseImageBtn = UIButton()
        choseImageBtn.layer.borderColor = UIColor.init(white: 0, alpha: 0.1).cgColor
        choseImageBtn.layer.borderWidth = 1
        choseImageBtn.layer.masksToBounds = true
        choseImageBtn.layer.cornerRadius = 4
        choseImageBtn.addTarget(self, action: #selector(didClickChoseImageBtn), for: .touchUpInside)
        scrollView.addSubview(choseImageBtn)
        choseImageBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(titleImageView)
        }
        let defaultImageView = UIImageView()
        defaultImageView.image = #imageLiteral(resourceName: "addImage_icon")
        choseImageBtn.addSubview(defaultImageView)
        defaultImageView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.height.equalTo(40)
        }
        
        let clearImageBtn = UIButton()
        clearImageBtn.setImage(#imageLiteral(resourceName: "clear_icon"), for: .normal)
        scrollView.addSubview(clearImageBtn)
        clearImageBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(titleImageView.snp_top)
            make.centerX.equalTo(titleImageView.snp_right)
            make.size.equalTo(CGSize(width: 40, height: 40))
        }
        clearImageBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            self.titleImageView.image = nil
        }).disposed(by: disposeBag)
        titleImageView.rx.observe(UIImage.self, "image").subscribe(onNext: { (image) in
            defaultImageView.isHidden = image != nil
            clearImageBtn.isHidden = image == nil
        }).disposed(by: disposeBag)
        
        let line3 = UIView()
        line3.backgroundColor = UIColor.init(white: 0, alpha: 0.1)
        scrollView.addSubview(line3)
        line3.snp.makeConstraints { (make) in
            make.top.equalTo(titleImageView.snp_bottom).offset(10)
            make.left.right.equalTo(self.view)
            make.height.equalTo(0.5)
        }
        
        let contentLabel = UILabel()
        contentLabel.font = .boldSystemFont(ofSize: 17)
        contentLabel.textColor = UIColor.init(white: 0, alpha: 0.7)
        contentLabel.text = "正文:"
        scrollView.addSubview(contentLabel)
        contentLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).inset(18)
            make.top.equalTo(line3.snp_bottom).offset(10)
            make.height.equalTo(34)
        }
        contentTextView.textColor = UIColor.init(white: 0, alpha: 0.8)
        contentTextView.font = UIFont(name: "PingFangSC-Light", size: 14)
        contentTextView.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
        contentTextView.layer.borderColor = UIColor.init(white: 0, alpha: 0.1).cgColor
        contentTextView.layer.borderWidth = 1
        scrollView.addSubview(contentTextView)
        contentTextView.snp.makeConstraints { (make) in
            make.top.equalTo(contentLabel.snp_bottom).offset(10)
            make.left.right.equalTo(self.view).inset(18)
            make.bottom.equalToSuperview().offset(-18)
            make.height.equalTo(self.view).multipliedBy(0.6)
        }
        NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification).subscribe(onNext: { (notification) in
            if self.contentTextView.isFirstResponder == false {
                return
            }
            let timeInterval = (notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
            let animationOption = (notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber).uintValue
            let keyboardHeight = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.size.height
            UIView.animate(withDuration: timeInterval, delay: 0, options: UIView.AnimationOptions(rawValue: animationOption), animations: {
                self.view.transform = CGAffineTransform.init(translationX: 0, y: -keyboardHeight)
            }, completion: nil)
        }).disposed(by: disposeBag)
        NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification).subscribe(onNext: { (notification) in
            let timeInterval = (notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
            let animationOption = (notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber).uintValue
            UIView.animate(withDuration: timeInterval, delay: 0, options: UIView.AnimationOptions(rawValue: animationOption), animations: {
                self.view.transform = CGAffineTransform.identity
            }, completion: nil)
        }).disposed(by: disposeBag)
    }
    
    @objc func endEdit() {
        self.pickerView?.removeFromSuperview()
        self.view.endEditing(true)
    }
    
    @objc func showSelectCategoryView() {
        endEdit()
        /*
        let pickerV = UIPickerView()
        pickerV.backgroundColor = UIColor.init(white: 0, alpha: 0.7)
        self.view.addSubview(pickerV)
        pickerV.snp.makeConstraints { (make) in
            make.height.equalTo(180)
            make.left.right.equalToSuperview()
            make.top.equalTo(self.view.snp_bottom)
        }
        self.view.layoutIfNeeded()
        self.view.setNeedsLayout()
        UIView.animate(withDuration: 0.25) {
            pickerV.snp.remakeConstraints { (make) in
                make.height.equalTo(180)
                make.left.right.equalToSuperview()
                make.bottom.equalTo(self.view.snp_bottom).offset(-(self.view.safeAreaInsets.bottom))
            }
            self.view.layoutIfNeeded()
            self.view.setNeedsLayout()
        }
        let modelObserver = BehaviorRelay<[STStoryCategoryModel]>(value: [])
        STStoryService().fetchStoryCategotyInfo().result { (models, error) in
            if let error = error {
                HUD.flash(.labeledError(title: nil, subtitle: error.localizedDescription))
                return
            }
            guard let models = models else {
                return
            }
            let array = Array(models.dropFirst())
            modelObserver.accept(array)
            var index = array.firstIndex(where: { $0.channelId == self.categoryModel.value.channelId })
            if index == nil {
                self.categoryModel.accept(array[0])
                index = 0
            }
            pickerV.selectRow(index!, inComponent: 0, animated: false)
        }
        modelObserver.bind(to: pickerV.rx.items) { (row, element, view) in
            guard let myView = view as? UILabel else {
                let view = UILabel()
                view.text = element.channelName
                view.textAlignment = .center
                view.textColor = .white
                view.font = .systemFont(ofSize: 21)
                return view
            }
            myView.text = element.channelName
            return myView
            }.disposed(by: disposeBag)
        pickerV.rx.itemSelected.subscribe(onNext: { (row: Int, component: Int) in
            self.categoryModel.accept(modelObserver.value[row])
        }).disposed(by: disposeBag)
        pickerView = pickerV
 */
        STStoryService().fetchStoryCategotyInfo().result { (models, error) in
            if let error = error {
                HUD.flash(.labeledError(title: nil, subtitle: error.localizedDescription))
                return
            }
            guard let models = models else {
                return
            }
            let array = Array(models.dropFirst())
            let actionSheet = UIAlertController(title: "分类", message: nil, preferredStyle: .actionSheet)
            actionSheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))

            for item in array {
                actionSheet.addAction(UIAlertAction(title: item.channelName, style: .default, handler: { (action) in
                    self.categoryModel.accept(array.filter({ (model) -> Bool in
                        return model.channelName == action.title!
                    }).first!)
                }))
            }
            self.present(actionSheet, animated: true, completion: nil)
        }
    }
    
    @objc func didClickChoseImageBtn() {
        endEdit()
        let imagePicker = CLImagePickerTool()
        imagePicker.singleImageChooseType = .singlePictureCrop
        imagePicker.singleModelImageCanEditor = true
        imagePicker.singlePictureCropScale = 16.0/9.0
        imagePicker.cl_setupImagePickerWith(MaxImagesCount: 6, superVC: self) { (asset, cutImage) in
            self.titleImageView.image = cutImage
        }
    }
    
    fileprivate let StoryTitleKey = "StoryTitleKey"
    fileprivate let StoryCategoryKey = "StoryCategoryKey"
    fileprivate let StoryImageKey = "StoryImageKey"
    fileprivate let StoryDetailKey = "StoryDetailKey"
    
    func initData() {
        let storyTitle = UserDefaults.standard.string(forKey: StoryTitleKey)
        self.titleField.text = storyTitle
        
        let categoryData = UserDefaults.standard.data(forKey: StoryCategoryKey)
        if categoryData != nil {
            let categoryModel = try? JSONDecoder().decode(STStoryCategoryModel.self, from: categoryData!)
            if categoryModel != nil {
                self.categoryModel.accept(categoryModel!)
            }
        }
        let storyImage = try? Data(contentsOf: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(StoryImageKey + ".png"))
        if storyImage != nil {
            let image = UIImage(data: storyImage!)
            self.titleImageView.image = image
        }
        
        let storyDetailData = try? Data(contentsOf: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(StoryDetailKey + ".txt"))
        if storyDetailData != nil {
            let content = String(data: storyDetailData!, encoding: .utf8)
            self.contentTextView.text = content ?? ""
        }
    }
    
    @objc func saveData() {
        UserDefaults.standard.set(self.titleField.text, forKey: StoryTitleKey)
        let categoryData = try? JSONEncoder().encode(self.categoryModel.value)
        UserDefaults.standard.set(categoryData, forKey: StoryCategoryKey)
        if self.titleImageView.image != nil {
            try? self.titleImageView.image!.pngData()?.write(to: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(StoryImageKey + ".png"))
        }
        if self.contentTextView.text != nil && self.contentTextView.text != "" {
            try? self.contentTextView.text.data(using: .utf8)?.write(to: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(StoryDetailKey + ".txt"))
        }
    }
    
    @objc func clearData() {
        UserDefaults.standard.set(nil, forKey: StoryTitleKey)
        self.titleField.text = nil
        UserDefaults.standard.set(nil, forKey: StoryCategoryKey)
        self.categoryModel.accept(STStoryCategoryModel(channelId: 2, channelName: "经典"))
        try? FileManager.default.removeItem(at: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(StoryImageKey + ".png"))
        self.titleImageView.image = nil
        try? FileManager.default.removeItem(at: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(StoryDetailKey + ".txt"))
        self.contentTextView.text = nil
    }
    
    @objc func publishData() {
        // 检查数据是否完整
        guard let title = self.titleField.text else {
            HUD.flash(.label("标题不能为空哦~"))
            return
        }
        if self.contentTextView.text.count < 30 {
            HUD.flash(.label("故事内容太少了呢...\n请多写点内容吧~"))
            return
        }
        // 是否登陆
        if STUserService.shareInstance.currentUser.value == nil {
            HUD.flash(.label("请登陆后再进行发布操作"))
            return
        }
        HUD.show(.labeledProgress(title: nil, subtitle: "发布中"))
        STStoryService().uploadStoryInfo(title: title, categoryId: self.categoryModel.value.channelId, image: self.titleImageView.image?.jpegData(compressionQuality: 0.4), content: self.contentTextView.text!).result { (error) in
            if error == nil {
                HUD.hide()
                self.clearData()
            } else {
                HUD.hide()
                HUD.flash(.labeledError(title: nil, subtitle: error?.localizedDescription))
            }
        }
    }
    
}
